﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using RN.ERP.Web.BasicService;
using RN.ERP.Web.EnterpriseService;
using System.ComponentModel;
using RN.ERP.Web.ModelService;
using RN.ERP.Web.PersonService;
using Newtonsoft.Json;
using RN.ERP.Web.Utilities;

namespace RN.ERP.Web.UserControl
{
    public partial class UCEnterpriseChange : BaseUserControl
    {
        #region 成员属性

        private BasicServiceClient basicService = new BasicServiceClient();
        private EnterpriseServiceClient corpService = new EnterpriseServiceClient();

        [Browsable(true)]     //该项属性是否会显示在控件的“属性”窗口中 
        [Description("功能类型Add、Edit、查看")]       //属性的说明  
        [BindableAttribute(true)]
        public FunctionTypeEnum FunctionType
        {
            get
            {
                return (FunctionTypeEnum)Enum.Parse(typeof(FunctionTypeEnum), Convert.ToString(hdnFunctionType.Value));
            }
            set { hdnFunctionType.Value = value.ToString(); }
        }

        [Browsable(true)]     //该项属性是否会显示在控件的“属性”窗口中 
        [Description("变更类型")]       //属性的说明  
        [BindableAttribute(true)]
        public ChangeTypeEnum ChangeType
        {
            get { return (ChangeTypeEnum)Enum.Parse(typeof(ChangeTypeEnum), Convert.ToString(this.hdnChangeType.Value)); }
            set { hdnChangeType.Value = value.ToString(); }
        }

        [BindableAttribute(true)]
        public string ObjectName
        {
            get { return hdnObjectName.Value; }
            set { hdnObjectName.Value = value; }
        }

        private string _objectId = string.Empty;

        [BindableAttribute(true)]
        public string ObjectId
        {
            get { return hdnID.Value; }
            set { hdnID.Value = value; }
        }

        private string _verifyFunType = string.Empty;
        [BindableAttribute(true)]
        public string VerifyFunType
        {
            get { return hdnVerifyFunType.Value; }
            set { hdnVerifyFunType.Value = value; }
        }

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                InitPage();
                AddOrUpdatePage();
                BindDDlCorpChangeItem();////绑定企业资质信息变更项
                GetOldValueToCompare();
                if (UserInfo.RoleType == "Manager")
                {
                    RequiredFieldValidator1.Visible = false;
                }
            }
        }

        private void InitPage()
        {
            if (base.UserInfo.RoleType == "Manager")
            {
                trEnterprise1.Visible = false;
                trEnterprise2.Visible = false;
                dvwCorpChangeList.Enabled = false;
                //spanReturn.Visible = false;
            }
            else
            {
                trEnterprise1.Visible = true;
                trEnterprise2.Visible = true;
                // spanReturn.Visible = true;
            }
            Verify1.SetID = hdnID.Value;
            Verify1.ChangeType = ChangeType;
            if (!string.IsNullOrWhiteSpace(Request.QueryString["flowCode"]))
            {
                hdnFlowCode.Value = Request.QueryString["flowCode"];
            }
            UseValidator("--请选择--");
            if (Request.QueryString["functionType"] == null)
            {
                Verify1.Visible = false;
            }

        }

        #region 控件事件

        protected void ddlCorpChangeItem_SelectedIndexChanged(object sender, EventArgs e)
        {
            string selecValue = ddlCorpChangeItem.SelectedValue.ToString();
            string[] arr = SplitChangeItemSelectValue(selecValue);
            if (arr != null && arr.Length > 0)
            {
                UseValidator(arr[0]);
                GetSubChangeControl(arr[1], arr[0]);
                string objectid = string.Empty;
                ////
                ////非添加时,objectId表示setid；hdnGuid=tb_ChangeSetRecord.ObjectId,也表示tb_changeItem表中BeforeSql中查询条件
                ////添加时，objectId表示被变更对象的唯一标识
                ////
                if (ChangeType.Equals(ChangeTypeEnum.Safe) || ChangeType.Equals(ChangeTypeEnum.Corp))
                {
                    objectid = UserInfo.CorpUserGuid;
                }
                else
                {
                    if (arr[2] == "6")
                    {
                        PersonServiceClient personService = new PersonServiceClient();
                        string managerjson = personService.GetPersonInfo(objectid, UserInfo.CurrentArea);
                        tb_Emp_Manager model = JsonConvert.DeserializeObject<tb_Emp_Manager>(managerjson);
                        objectid = model.EmpGuid.ToString();
                        // this.InfoChange1.ObjectId = strId;
                        ChangeType = ChangeTypeEnum.PersonQualityB;
                    }
                    else if (!FunctionType.Equals(FunctionTypeEnum.Add))
                    {
                        objectid = hdnObjectId.Value;
                    }
                    else
                    {
                        objectid = hdnID.Value;
                    }

                    if (arr[2].Equals("3"))
                    {
                        trsafe.Visible = true;
                        trbefore.Visible = false;
                    }
                    else if (arr[2].Equals("2"))
                    {
                        trsafe.Visible = false;
                        trbefore.Visible = true;
                    }
                    else
                    {
                        trsafe.Visible = false;
                        trbefore.Visible = false;
                    }
                }
                FindOldValueBySelectItem(objectid, arr[0]);
                GetOldValueToCompare();
            }
        }

        /// <summary>
        /// 添加到GridView
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_addRecord_Click(object sender, EventArgs e)
        {
            if (CheckTextLen())
            {
                if (CheckInfo())
                {
                    string afterChangeTitle = string.Empty;
                    string afterChangeValue = string.Empty;
                    string beforeValue = hdnBeforeValue.Value;
                    if (ddlChange.Visible == true && !string.IsNullOrWhiteSpace(ddlChange.SelectedValue))
                    {
                        afterChangeTitle = ddlChange.SelectedItem.Text.ToString();
                        afterChangeValue = ddlChange.SelectedValue.ToString();
                    }
                    else if (TChangeDate.Visible == true)
                    {
                        afterChangeTitle = TChangeDate.SelectedDate.Value.ToShortDateString();
                        afterChangeValue = TChangeDate.SelectedDate.Value.ToShortDateString();
                    }
                    else if (ckboxafter.Visible == true)
                    {
                        #region 获取变更后iso认证
                        ListItem item = ckboxafter.Items.FindByText("bISO14000");
                        if (item != null)
                        {
                            afterChangeTitle += (item.Selected ? "1" : "0") + ",";
                            afterChangeValue += (item.Selected ? "1" : "0") + ",";
                        }
                        item = ckboxafter.Items.FindByText("bISO9000");
                        if (item != null)
                        {
                            afterChangeTitle += (item.Selected ? "1" : "0") + ",";
                            afterChangeValue += (item.Selected ? "1" : "0") + ",";
                        }
                        item = ckboxafter.Items.FindByText("bISO9001");
                        if (item != null)
                        {
                            afterChangeTitle += (item.Selected ? "1" : "0") + ",";
                            afterChangeValue += (item.Selected ? "1" : "0") + ",";
                        }
                        item = ckboxafter.Items.FindByText("bOHSMS18000");
                        if (item != null)
                        {
                            afterChangeTitle += item.Selected ? "1" : "0";
                            afterChangeValue += item.Selected ? "1" : "0";
                        }
                        #endregion
                        #region 获取变更前iso认证
                        ListItem item1 = ckboxbefore.Items.FindByText("bISO14000");
                        if (item1 != null)
                        {
                            hdnBeforeKey.Value += (item1.Selected ? "1" : "0") + ",";
                        }
                        item1 = ckboxbefore.Items.FindByText("bISO9000");
                        if (item1 != null)
                        {
                            hdnBeforeKey.Value += (item1.Selected ? "1" : "0") + ",";
                        }
                        item1 = ckboxbefore.Items.FindByText("bISO9001");
                        if (item1 != null)
                        {
                            hdnBeforeKey.Value += (item1.Selected ? "1" : "0") + ",";
                        }
                        item1 = ckboxbefore.Items.FindByText("bOHSMS18000");
                        if (item1 != null)
                        {
                            hdnBeforeKey.Value += (item1.Selected ? "1" : "0") + ",";
                        }
                        beforeValue = this.hdnBeforeKey.Value;
                        #endregion
                    }
                    else
                    {
                        afterChangeTitle = txtChange.Text.Trim();
                        afterChangeValue = txtChange.Text.Trim();
                    }
                    string[] arr = SplitChangeItemSelectValue(ddlCorpChangeItem.SelectedValue);
                    List<Tb_ChangeRecord> chgRcdList = (List<Tb_ChangeRecord>)ViewState["chgRcdList"];
                    TransListToTable(ref chgRcdList, this.hdnBeforeKey.Value, beforeValue, afterChangeTitle, afterChangeValue, arr[0], ddlCorpChangeItem.SelectedItem.Text.ToString(), txtRemark.Text.Trim(), arr[2]);
                }
                else
                { ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "", "alert('请填写变更信息！');", true); return; }
            }
        }

        /// <summary>
        ///上报
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnNext_Click(object sender, EventArgs e)
        {
            if (CheckTextLen())
            {
                List<Tb_ChangeRecord> chgRcdList = (List<Tb_ChangeRecord>)ViewState["chgRcdList"];
                if (chgRcdList == null || chgRcdList.Count == 0)
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('请先添加变更申请才可以上报！');", true);
                    return;
                }
                if (!FunctionType.Equals(FunctionTypeEnum.Add))////修改
                    EditChangeList();
                else////添加
                    ComitChangeInfoList();
            }
        }

        public bool CheckTextLen()
        {
            if (txtChangeRemark.Text.Trim().Length > 500)
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('变更情况说明过长，请控制在500字以内!');", true);
                return false;
            }
            if (ddlCorpChangeItem.SelectedValue != null && (!ddlCorpChangeItem.SelectedValue.Contains("Introduction") && !ddlCorpChangeItem.SelectedValue.Contains("BussinessArea")))
            {
                if (!string.IsNullOrEmpty(txtChange.Text) && txtChange.Text.Length > 100)
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('变更内容过长，请控制在100字以内!');", true);
                    return false;
                }
            }
            if (string.IsNullOrWhiteSpace(hdnFunctionType.Value))
            {
                return false;
            }
            if (!string.IsNullOrEmpty(txtBefore.Text) && txtBefore.Text.Length > 2000)
            {
                txtBefore.Text = txtBefore.Text.Substring(0, 1800) + ".....";
            }
            if (!string.IsNullOrEmpty(txtChange.Text) && txtChange.Text.Length > 2000)
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('变更内容过长，请控制在2000字以内!');", true);
                return false;
            }
            return true;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void dvwCorpChangeList_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            switch (e.CommandName.ToLower())
            {
                case "del":
                    List<Tb_ChangeRecord> chgRcdList = (List<Tb_ChangeRecord>)ViewState["chgRcdList"];
                    if (chgRcdList != null && chgRcdList.Count > 0)
                    {
                        chgRcdList.RemoveAt(int.Parse(e.CommandArgument.ToString()));
                        BindDvwChangeRecords(chgRcdList);
                    }
                    break;
            }
        }

        protected void ddlCorpChangeItemSub_SelectedIndexChanged(object sender, EventArgs e)
        {
            //txtChange.CssClass = "";
            //if (ddlCorpChangeItemSub.SelectedValue.Equals("0"))
            //{
            //    txtBefore.Visible = true;
            //    txtChange.Text = string.Empty;
            //    txtChange.Visible = true;
            //    txtChange.Attributes["onclick"] = "SelectFrEmp(this)";
            //    txtChange.Attributes["contenteditable"] = "false";
            //    // GetBeforeCorpBaseInfo(base.UserGuid, ddlCorpChangeItem.SelectedValue);
            //}
            //else if (ddlCorpChangeItemSub.SelectedValue.Equals("1"))////非库中已有人员
            //{
            //    txtBefore.Visible = true;
            //    txtChange.Text = "添加企业管理人员";
            //    txtChange.Visible = true;
            //    txtChange.CssClass = "txtchange";
            //    txtChange.Attributes.Add("onclick", " window.showModalDialog('../Person/PersonAdd.aspx', null, 'center:yes;dialogHeight:600px; dialogwidth:600px;help:no;status: no ; ');");
            //}
            //else
            //{
            //    txtChange.Attributes["onclick"] = "";
            //    txtChange.Attributes["contenteditable"] = "true";
            //}
        }

        #endregion

        #region 页面调用方法

        private void ComitChangeInfoList()
        {
            string operationResult = string.Empty;
            List<Tb_ChangeRecord> chgRcdList = (List<Tb_ChangeRecord>)ViewState["chgRcdList"];
            if (chgRcdList != null && chgRcdList.Count > 0)
            {
                List<Tb_ChangeSetRecord> changeSetList = CreateChangeSetRecord(chgRcdList);
                if (changeSetList != null && changeSetList.Count > 0)
                {
                    for (int i = 0; i < changeSetList.Count; i++)
                    {
                        IList<Tb_ChangeRecord> changes = chgRcdList.FindAll(m => m.ClassID == int.Parse(changeSetList[i].ObjectType));

                        if (changes != null)
                        {
                            string strChange = JsonConvert.SerializeObject(changes.ToList());
                            string strChangeSet = JsonConvert.SerializeObject(changeSetList[i]);
                            operationResult = basicService.AddChange(strChangeSet, strChange, ((ChangeTypeEnum)int.Parse(changeSetList[i].ObjectType)).ToString(), UserInfo.CorpUserGuid, UserInfo.RoleId, UserInfo.UserName, UserInfo.CurrentArea);
                        }
                    }
                }
                if (!string.IsNullOrWhiteSpace(operationResult) && !operationResult.Equals("null"))
                {
                    OperationResult opr = JsonConvert.DeserializeObject<OperationResult>(operationResult);
                    if (opr.Result)
                    {
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('" + opr.Message + "');" + ReturnBack() + ";", true);
                    }
                    else
                    {
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('" + opr.Message + "');", true);
                    }
                }
                else
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('添加失败！');", true);
                }
            }
        }

        private string ReturnBack()
        {
            string returnurl = "";
            switch (ChangeType)
            {
                case ChangeTypeEnum.Corp:
                case ChangeTypeEnum.Safe:
                    returnurl = "location.href='../EnterpriseChange/ChangeInfo.aspx';";
                    break;
                case ChangeTypeEnum.CorpQuality:
                    returnurl = "location.href='../Enterprise/EnterpriseQualityAllInfoNew.aspx';";
                    break;
                case ChangeTypeEnum.Person:
                case ChangeTypeEnum.PersonQualityB:
                    returnurl = "location.href='../PersonChange/ChangeList.aspx';";
                    break;
                case ChangeTypeEnum.PersonQuality:
                    returnurl = "location.href='../Person/PersonQualityChangeListNew.aspx';";
                    break;
                default:
                    break;
            }

            return returnurl;
        }

        /// <summary>
        /// 编辑，查看，添加 不同界面
        /// </summary>
        private void AddOrUpdatePage()
        {
            ////变更前字段信息
            if (this.ChangeType.Equals(ChangeTypeEnum.CorpQuality))
            {
                trbefore.Visible = true;
                trsafe.Visible = false;
            }
            else if (this.ChangeType.Equals(ChangeTypeEnum.Safe))
            {
                trbefore.Visible = false;
                trsafe.Visible = true;
            }
            ////变更前字段信息
            if (!string.IsNullOrWhiteSpace(hdnID.Value) && !FunctionType.Equals(FunctionTypeEnum.Add))//从变更集合页进入
            {
                ////修改/查看
                GetRecordsByParentID(hdnID.Value);
            }
        }

        private void BindDvwChangeRecords(List<Tb_ChangeRecord> chgRcdList)
        {
            dvwCorpChangeList.DataSource = chgRcdList;
            dvwCorpChangeList.DataBind();
            ViewState["chgRcdList"] = chgRcdList;
            if (hdnFunctionType.Value.Equals("View") && base.UserInfo.RoleType == "Manager")
            {
                dvwCorpChangeList.Columns[dvwCorpChangeList.Columns.Count - 1].Visible = false;
            }
        }

        /// <summary>
        /// 绑定企业信息变更项
        /// </summary>
        private void BindDDlCorpChangeItem()
        {
            bool isouterCorp = true;
            string changeItems = string.Empty;
            if (ChangeType == ChangeTypeEnum.Corp)
            {
                changeItems = "Corp,Safe";
                if (base.UserInfo.AreaCode == base.UserInfo.CurrentArea)//本地企业
                {
                    isouterCorp = false;
                }
                else
                {
                    changeItems = "Corp,Safe,CorpWdrq";
                }
            }
            else if (ChangeType == ChangeTypeEnum.Person)
            {
                changeItems = "Person,PersonQualityB";
            }
            else
            {
                changeItems = Enum.GetName(typeof(ChangeTypeEnum), ChangeType);
            }
            string dicItemsStr = basicService.GetChangeItems(changeItems, "0",UserInfo.CurrentArea);
            if (!string.IsNullOrWhiteSpace(dicItemsStr) && !dicItemsStr.Equals("null"))
            {
                IList<Tb_ChangeItem> Items = JsonConvert.DeserializeObject<IList<Tb_ChangeItem>>(dicItemsStr);
                if (Items != null && Items.Count > 0)
                {
                    //if (!isouterCorp)
                    //{
                    //    ////从web.config中读取下拉项个数
                    //    int takeNum = 0;
                    //    if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["CorpTakeNum"]))
                    //    {
                    //        takeNum = int.Parse(ConfigurationManager.AppSettings["CorpTakeNum"]);
                    //    }
                    //    Items = Items.Take(takeNum).ToList();
                    //}
                    Items = Items.Select(r => new Tb_ChangeItem
                    {
                        ChangeItemName = r.ChangeItemName,
                        ChangeItem = r.ChangeItem + "|" + r.ClassValue + "|" + r.ItemType
                    }).ToList();
                    ddlCorpChangeItem.DataSource = Items.ToList();
                    ddlCorpChangeItem.DataTextField = "ChangeItemName";
                    ddlCorpChangeItem.DataValueField = "ChangeItem";
                    ddlCorpChangeItem.DataBind();
                    ddlCorpChangeItem.Items.Insert(0, new ListItem("--请选择--", "-1"));
                    ViewState["ChangeItemList"] = Items.ToList();
                }
            }
        }

        /// <summary>
        /// 判断变更项是否填写正确
        /// </summary>
        /// <returns></returns>
        private bool CheckInfo()
        {
            bool flag = true;
            if (ddlCorpChangeItem.SelectedIndex < 0) flag = false;
            if (txtChange.Visible == true && string.IsNullOrWhiteSpace(txtChange.Text.Trim())) flag = false;
            if (ddlChange.Visible == true && ddlChange.SelectedIndex < 0) flag = false;
            if (TChangeDate.Visible == true && (TChangeDate.SelectedDate == null || string.IsNullOrWhiteSpace(TChangeDate.SelectedDate.Value.ToString()))) flag = false;
            return flag;
        }

        private void EditChangeList()
        {
            string operationResult = string.Empty;
            List<Tb_ChangeRecord> chgRcdList = (List<Tb_ChangeRecord>)ViewState["chgRcdList"];
            if (chgRcdList != null && chgRcdList.Count > 0)
            {
                List<Tb_ChangeSetRecord> changeSetList = CreateChangeSetRecord(chgRcdList);
                if (changeSetList != null && changeSetList.Count > 0)
                {
                    for (int i = 0; i < changeSetList.Count; i++)
                    {
                        IList<Tb_ChangeRecord> changes = chgRcdList.FindAll(m => m.ClassID == int.Parse(changeSetList[i].ObjectType));
                        if (changes != null)
                        {
                            string strChange = JsonConvert.SerializeObject(changes.ToList());
                            string strChangeSet = JsonConvert.SerializeObject(changeSetList[i]);
                            operationResult = basicService.EditChange(strChangeSet, strChange, ((ChangeTypeEnum)int.Parse(changeSetList[i].ObjectType)).ToString(), base.UserInfo.CorpUserGuid, base.UserInfo.RoleId, base.UserInfo.UserName, UserInfo.CurrentArea);
                        }
                    }
                }
                if (!string.IsNullOrWhiteSpace(operationResult) && !operationResult.Equals("null"))
                {
                    OperationResult result = JsonConvert.DeserializeObject<OperationResult>(operationResult);
                    if (result.Result)
                    {
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('" + result.Message + "');" + ReturnBack() + ";", true);
                    }
                    else
                    {
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('" + result.Message + "');", true);
                    }
                }
                else
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('修改失败！');", true);
                }
            }

        }

        private void GetSubChangeControl(string classValue, string selectValue)
        {
            string result = string.Empty;
            SetControlVisible(false);
            switch (classValue)
            {
                case "2":////时间
                    TChangeDate.Visible = true;
                    TChangeDate.Clear();
                    TChangeDate.Width = 200;
                    txtChange.Visible = false;
                    txtChange.Text = string.Empty;
                    ddlChange.ClearSelection();
                    ddlChange.Visible = false;
                    ckboxbefore.Visible = false;
                    ckboxafter.Visible = false;
                    break;
                case "3":////下拉菜单
                    TChangeDate.Visible = false;
                    TChangeDate.Width = 0;
                    TChangeDate.Clear();
                    txtChange.Visible = false;
                    txtChange.Text = string.Empty;
                    ddlChange.Visible = true;
                    ddlChange.SelectedIndex = 0;
                    ckboxbefore.Visible = false;
                    ckboxafter.Visible = false;
                    if (selectValue == "sex")
                    {
                        ListItem item1 = new ListItem("男", "1");
                        ListItem item2 = new ListItem("女", "0");
                        ddlChange.Enabled = true;
                        ddlChange.Items.Clear();
                        ddlChange.Items.Add(item1);
                        ddlChange.Items.Add(item2);
                    }
                    else
                    {
                        string condition = GetBindChangeValueByChangeType(selectValue);
                        result = corpService.GetBindChangeValue(selectValue, UserInfo.CurrentArea, new string[] { condition });////????????
                        if (!string.IsNullOrWhiteSpace(result) && !result.Equals("null"))
                        {
                            Dictionary<string, string> dicResult = JsonConvert.DeserializeObject<Dictionary<string, string>>(result);
                            if (dicResult != null && dicResult.Count > 0)
                            {
                                ddlChange.Enabled = true;
                                ddlChange.Items.Clear();
                                ddlChange.DataSource = dicResult;
                                ddlChange.DataTextField = "value";
                                ddlChange.DataValueField = "key";
                                ddlChange.DataBind();
                            }
                        }
                    }
                    break;
                case "4":
                    txtBefore.Visible = false;
                    ckboxbefore.Visible = true;
                    ddlChange.Visible = false;
                    txtChange.Visible = false;
                    TChangeDate.Visible = false;
                    ckboxafter.Visible = true;
                    break;
                default:
                    SetControlVisible(false);
                    txtChange.Visible = true;
                    ckboxbefore.Visible = false;
                    ckboxafter.Visible = false;
                    break;
            }
        }

        private string GetBindChangeValueByChangeType(string selectValue)
        {
            string condition = string.Empty;
            if (ChangeType.Equals(ChangeTypeEnum.CorpQuality))
            {
                if (selectValue.Equals("QualityBusiness"))
                {
                    condition = GetMajorName(base.UserInfo.RoleId);////查询资质专业类型
                }
                else
                {
                    condition = GetRoleName(base.UserInfo.RoleId);////查询企业资质等级
                }
            }
            return condition;
        }

        /// <summary>
        /// 变更详细
        /// </summary>
        /// <param name="changeSetId"></param>
        private void GetRecordsByParentID(string changeSetId)
        {
            string result = string.Empty;
            if (FunctionType.Equals(FunctionTypeEnum.View) && hdnFlowCode.Value.IndexOf("21") < 0) ////查看
            {
                btn_addRecord.Visible = false;
                btnNext.Visible = false;
                dvwCorpChangeList.Columns[6].Visible = false;
                //spanReturn.Visible = true;
                //spanReturn.Attributes.Add("onclick", ReturnBack());
            }
            if (!string.IsNullOrWhiteSpace(hdnID.Value))
            {
                result = corpService.GetChangeDetails(Enum.GetName(typeof(ChangeTypeEnum), ChangeType), int.Parse(hdnID.Value), UserInfo.CurrentArea);
                if (!string.IsNullOrWhiteSpace(result) && !result.Equals("null"))
                {
                    ChangeDetail chDtl = JsonConvert.DeserializeObject<ChangeDetail>(result);
                    List<Tb_ChangeRecord> recList = chDtl.ChangeInfos.ToList<Tb_ChangeRecord>();
                    if (recList != null && recList.Count > 0)
                    {
                        BindDvwChangeRecords(recList);
                        hdnObjectId.Value = chDtl.ChangeSet.ObjectId;
                        txtChangeRemark.Text = chDtl.ChangeSet.Description;
                    }
                }
            }
        }

        private void FindOldValueBySelectItem(string id, string selectColumn)
        {
            if (selectColumn.Equals("-1")) return;
            string dicResultStr = corpService.GetBeforeChangeValue(selectColumn, UserInfo.CurrentArea, new string[] { id });
            Dictionary<string, string> result = JsonConvert.DeserializeObject<Dictionary<string, string>>(dicResultStr);
            hdnBeforeKey.Value = string.Empty;
            hdnBeforeValue.Value = string.Empty;
            if (!string.IsNullOrWhiteSpace(dicResultStr) && !dicResultStr.Equals("null"))
            {
                if (selectColumn.ToLower() == "biso")
                {
                    if (!string.IsNullOrEmpty(result.Keys.First()))
                    {
                        string[] isolist = result.Keys.First().Split('|');
                        ListItem item;
                        item = ckboxbefore.Items.FindByText("bISO14000");
                        if (item != null)
                        {
                            item.Selected = (isolist[0] == "1") ? true : false;
                        }
                        item = ckboxbefore.Items.FindByText("bISO9000");
                        if (item != null)
                        {
                            item.Selected = (isolist[1] == "1") ? true : false;
                        }
                        item = ckboxbefore.Items.FindByText("bISO9001");
                        if (item != null)
                        {
                            item.Selected = (isolist[2] == "1") ? true : false;
                        }
                        item = ckboxbefore.Items.FindByText("bOHSMS18000");
                        if (item != null)
                        {
                            item.Selected = (isolist[3] == "1") ? true : false;
                        }
                    }
                }
                else
                {
                    txtBefore.Visible = true;
                    if (result.Keys.Count > 0 && result.Values.Count > 0 && !string.IsNullOrEmpty(result.Keys.First()) && !string.IsNullOrEmpty(result.Values.First()))
                    {
                        txtBefore.Text = result.Keys.First().Length <= 2000 ? result.Keys.First() : result.Keys.First().Substring(0, 2000) + ".....";
                        hdnBeforeKey.Value = txtBefore.Text;
                        hdnBeforeValue.Value = result.Values.First().Length <= 2000 ? result.Values.First() : result.Values.First().Substring(0, 2000) + ".....";
                    }
                }
            }
        }

        private void SetControlVisible(bool flag)
        {
            //变更前项目
            valr.Enabled = flag;
            txtBefore.Text = string.Empty;
            txtRemark.Text = string.Empty;
            //txtChangeRemark.Text = string.Empty;
            txtChange.Text = string.Empty;
            txtBefore.ReadOnly = true;
            ddlChange.Visible = flag;
            ddlChange.Visible = flag;
            txtChange.Visible = flag;
            TChangeDate.Visible = false;
            TChangeDate.Width = 0;
            //  ddlCorpChangeItemSub.Visible = flag;
            txtChange.Attributes["onclick"] = "";
            txtChange.Attributes["contenteditable"] = "true";

        }

        /// <summary>
        /// 变更申请集合存入DataTable
        /// </summary>
        /// <param name="chgRcdList"></param>
        /// <returns></returns>
        private void TransListToTable(ref List<Tb_ChangeRecord> chgRcdList, string BeforeChange, string BeforeValue, string AfterChangeTitle, string AfterChangeValue, string ChangeItem, string ChangeItemName, string Remark, string ItemType)
        {
            if (chgRcdList == null)
                chgRcdList = new List<Tb_ChangeRecord>();
            if (chgRcdList != null && chgRcdList.Count > 0 && chgRcdList.Find(m => m.ChangeItem.Equals(ChangeItem)) != null)
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('列表中已添加相同项目！');", true);
            }
            else
            {
                ////创建变更申请实体
                Tb_ChangeRecord rec = CreateChangeRecord(BeforeChange, BeforeValue, AfterChangeTitle, AfterChangeValue, ChangeItem, ChangeItemName, Remark, ItemType);
                ////放入变更申请集合List中
                chgRcdList.Add(rec);
                BindDvwChangeRecords(chgRcdList);
            }
        }

        private static Tb_ChangeRecord CreateChangeRecord(string BeforeChange, string BeforeValue, string AfterChangeTitle, string AfterChangeValue, string ChangeItem, string ChangeItemName, string Remark, string ItemType)
        {
            Tb_ChangeRecord rec = new Tb_ChangeRecord();

            if (ChangeItem.ToLower() == "biso")
            {
                #region 变更后iso认证
                if (!string.IsNullOrEmpty(AfterChangeTitle))
                {
                    string[] after = AfterChangeTitle.Split(',');
                    if (after[0] == "1")
                    {
                        rec.AfterChange += "bISO14000,";
                    }
                    if (after[1] == "1")
                    {
                        rec.AfterChange += "bISO9000,";
                    }
                    if (after[2] == "1")
                    {
                        rec.AfterChange += "bISO9001,";
                    }
                    if (after[3] == "1")
                    {
                        rec.AfterChange += "bOHSMS18000";
                    }
                }
                rec.AfterValue = AfterChangeValue;
                #endregion
                #region 变更前iso认证
                if (!string.IsNullOrEmpty(BeforeChange))
                {
                    string[] before = BeforeChange.Split(',');
                    if (before[0] == "1")
                    {
                        rec.BeforeChange += "bISO14000,";
                    }
                    if (before[1] == "1")
                    {
                        rec.BeforeChange += "bISO9000,";
                    }
                    if (before[2] == "1")
                    {
                        rec.BeforeChange += "bISO9001,";
                    }
                    if (before[3] == "1")
                    {
                        rec.BeforeChange += "bOHSMS18000";
                    }
                    rec.BeforeValue = BeforeValue;
                }
                #endregion
            }
            else
            {
                rec.AfterChange = !string.IsNullOrEmpty(AfterChangeTitle) && AfterChangeTitle.Length > 2000 ? AfterChangeTitle.Substring(0, 2000) : AfterChangeTitle;
                rec.AfterValue = !string.IsNullOrEmpty(AfterChangeValue) && AfterChangeValue.Length > 2000 ? AfterChangeValue.Substring(0, 2000) : AfterChangeValue;
                rec.BeforeChange = BeforeChange;
                rec.BeforeValue = BeforeValue;
            }
            rec.ChangeItem = ChangeItem;
            rec.ChangeItemName = ChangeItemName;
            rec.ClassID = string.IsNullOrWhiteSpace(ItemType) ? -1 : int.Parse(ItemType);
            //rec.ChangeItemSubCode
            // rec.ExtensionData
            //rec.OptID = ;
            //rec.OptDate
            rec.Remark = Remark;
            return rec;
        }

        private List<Tb_ChangeSetRecord> CreateChangeSetRecord(List<Tb_ChangeRecord> recList)
        {
            if (recList == null || recList.Count <= 0)
            {
                return null;
            }
            List<Tb_ChangeSetRecord> changeSetList = new List<Tb_ChangeSetRecord>();
            for (int i = 0; i < recList.Count; i++)
            {
                if (changeSetList.Count > 0 && changeSetList.Where(m => m.ObjectType == recList[i].ClassID.ToString()).FirstOrDefault() != null)
                {
                    continue;
                }
                else
                {
                    Tb_ChangeSetRecord changeSet = new Tb_ChangeSetRecord();
                    if (!string.IsNullOrWhiteSpace(hdnID.Value) && hdnID.Value != null && !FunctionType.Equals(FunctionTypeEnum.Add))
                    {
                        changeSet.Id = int.Parse(hdnID.Value);
                    }
                    if (!FunctionType.Equals(FunctionTypeEnum.Add))
                    {
                        changeSet.ObjectId = this.hdnObjectId.Value;
                    }
                    else if (recList[i].ClassID.ToString() == "6")
                    {
                        //人员资格B证
                        PersonServiceClient personService = new PersonServiceClient();
                        string managerjson = personService.GetPersonInfo(this.hdnID.Value, UserInfo.CurrentArea);
                        tb_Emp_Manager model = JsonConvert.DeserializeObject<tb_Emp_Manager>(managerjson);
                        changeSet.ObjectId = model.EmpGuid.ToString();
                    }
                    else
                    {
                        changeSet.ObjectId = this.hdnID.Value;
                    }
                    //changeSet.ObjectId = this.hdnID.Value;
                    changeSet.ObjectType = recList[i].ClassID.ToString();
                    changeSet.ObjectName = hdnObjectName.Value;
                    changeSet.IsrtUserId = base.UserInfo.CorpUserGuid;
                    changeSet.IsrtUserName = base.UserInfo.UserName;
                    changeSet.IsDel = false;
                    changeSet.IsrtDate = DateTime.Now;
                    changeSet.Description = txtChangeRemark.Text.Trim();
                    changeSetList.Add(changeSet);
                }
            }

            //if (!string.IsNullOrWhiteSpace(hdnID.Value) && hdnID.Value != null && !FunctionType.Equals(FunctionTypeEnum.Add))
            //{
            //    changeSet.Id = int.Parse(hdnID.Value);
            //}
            //if (!FunctionType.Equals(FunctionTypeEnum.Add))
            //{
            //    changeSet.ObjectId = this.hdnObjectId.Value;
            //}
            //else
            //{
            //changeSet.ObjectId = this.hdnID.Value;
            //}

            return changeSetList;
        }

        /// <summary>
        /// 设置非此类变更项的子选择不可见
        /// </summary>
        /// <param name="selecValue"></param>
        private void UseValidator(string selecValue)
        {

            if (this.FindControl("pnlValidate").Controls.Count > 0)
            {
                for (int i = 0; i < this.FindControl("pnlValidate").Controls.Count; i++)
                {
                    if (this.FindControl("pnlValidate").Controls[i] != null && this.FindControl("pnlValidate").Controls[i].GetType().Name.Equals("RegularExpressionValidator"))
                    {
                        RegularExpressionValidator vale = (RegularExpressionValidator)this.FindControl("pnlValidate").Controls[i];
                        if (ddlCorpChangeItem.SelectedValue != null && string.IsNullOrEmpty(ddlCorpChangeItem.SelectedValue))
                        {
                            vale.Enabled = false;
                            vale.Visible = false;
                            valr.Enabled = false;
                            valr.Visible = false;
                        }
                        else
                        {
                            if (this.FindControl("pnlValidate").Controls[i].ID.Equals("vale" + selecValue))
                            {

                                vale.Enabled = true;
                                vale.Visible = true;
                            }
                            else
                            {
                                vale.Enabled = false;
                                vale.Visible = false;
                            }
                        }
                    }
                }
            }
        }

        private string[] SplitChangeItemSelectValue(string selectValue)
        {
            if (string.IsNullOrWhiteSpace(selectValue) || selectValue.Equals("-1"))
            {
                return null;
            }
            string[] arr = selectValue.ToString().Split('|');
            if (arr == null || arr.Length == 0)
            {
                return null;
            }
            else
            {
                return arr;
            }
        }


        public void GetOldValueToCompare()
        {
            if (ChangeType.Equals(ChangeTypeEnum.CorpQuality) && trbefore.Visible)
            {
                string oldValueID = string.Empty;
                if (!FunctionType.Equals(FunctionTypeEnum.Add))
                {
                    oldValueID = hdnObjectId.Value;
                }
                else
                {
                    oldValueID = hdnID.Value;
                }
                string quaBeforeStr = corpService.GetCorpQuality(oldValueID, UserInfo.CurrentArea);
                if (!string.IsNullOrWhiteSpace(quaBeforeStr) && !quaBeforeStr.Equals("null"))
                {
                    tb_Corp_Quality quality = JsonConvert.DeserializeObject<tb_Corp_Quality>(quaBeforeStr);
                    if (quality != null)
                    {
                        lblIsMain.Text = (bool)quality.IsMain ? "是" : "否";
                        lblQuaName.Text = quality.DetailName;
                        lblQuaLevel.Text = quality.GradeName;
                        lblStartTime.Text = string.IsNullOrWhiteSpace(quality.GetDate.ToString()) ? "暂无" : quality.GetDate.Value.ToShortDateString();
                        lblEndTime.Text = string.IsNullOrWhiteSpace(quality.zzzEndDate.ToString()) ? "暂无" : quality.zzzEndDate.Value.ToShortDateString();
                    }
                }
            }
            else if (ChangeType.Equals(ChangeTypeEnum.Corp) && trsafe.Visible)
            {
                string quaBeforeStr = corpService.GetCorpSecurity(base.UserInfo.CorpUserGuid, UserInfo.CurrentArea);
                if (!string.IsNullOrWhiteSpace(quaBeforeStr) && !quaBeforeStr.Equals("null"))
                {
                    Kh_CorpTable kh = JsonConvert.DeserializeObject<Kh_CorpTable>(quaBeforeStr);
                    if (kh != null)
                    {
                        lblSafeNo.Text = kh.SafeLicenceNo;
                        lblSafeDate.Text = string.IsNullOrWhiteSpace(kh.LicenceEndDate.ToString()) ? "暂无" : kh.LicenceEndDate.Value.ToString("yyyy-mm-dd");
                    }
                }
            }
            else
            {
                trbefore.Visible = false;
                trsafe.Visible = false;
            }
        }

        #endregion

        protected void dvwCorpChangeList_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                LinkButton LinkButton1 = e.Row.FindControl("LinkButton1") as LinkButton;

                if (UserInfo.RoleType == "Manager")
                {
                    LinkButton1.Visible = false;
                }
                else if (Request.QueryString["flowcode"] != null)
                {
                    string flowcode = Request.QueryString["flowcode"].ToString();
                    if (!flowcode.StartsWith("0,019,021"))
                    {
                        if (flowcode.StartsWith("1") || flowcode.IndexOf("022") > 0 || flowcode.StartsWith("0,019"))
                        {
                            LinkButton1.Visible = false;
                        }
                    }
                }
            }
        }

        #region 企业资质，角色
        /// <summary>
        /// 资质等级
        /// </summary>
        /// <param name="roleid"></param>
        /// <returns></returns>
        public string GetRoleName(string roleid)
        {
            string result = string.Empty;
            switch (roleid)
            {
                case "30": result = "YBHNTZZDJ"; break;
                case "31": result = "HNTYZGJZZDJ"; break;
                case "55": result = "DJZZDJ"; break;
                case "42": result = "JLZZDJ"; break;
                case "47": result = "KCZZDJ"; break;
                case "99105":
                case "105": result = "ZBDLZZDJ"; break;
                case "46": result = "ZJZXZZDJ"; break;
                case "17":
                case "15": result = "ZZDJ"; break;
                default: break;
            }

            return result;
        }

        /// <summary>
        /// 资质专业
        /// </summary>
        /// <param name="roleid"></param>
        /// <returns></returns>
        public string GetMajorName(string roleid)
        {
            string result = string.Empty;
            switch (roleid)
            {
                ////case "30": result = "YBHNTZZDJ"; break;
                ////case "31": result = "HNTYZGJZZDJ"; break;
                case "55": result = "1055"; break;
                case "42": result = "1021"; break;
                //// case "47": result = "KCZZDJ"; break;
                case "99105":
                case "105": result = "1105"; break;
                case "46": result = "1046"; break;
                case "17":
                case "15": result = "1000"; break;
                case "7330":
                    result = "1021";
                    break;
                default: break;
            }

            return result;
        }

        #endregion
    }
}
